// pages/comfirm-order/comfirm-order.js
import {
  getDeliveryFee,
  getWXappPay,
  wXappUpdateOrder
} from '../../api/apis.js'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    buys: [],
    addressDetail: {}
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this._getAddress()
    this._getConfirmProduct()
    this._getDeliveryFee()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this._getAddress()
    this._getConfirmProduct()
    this._getDeliveryFee()
  },
  _getAddress() {
    let address = wx.getStorageSync("address")
    if (address) {
      this.setData({
        addressDetail: address
      })
    }
  },
  _getConfirmProduct() {
    let buys = wx.getStorageSync("confirmProduct")
    let ids = []
    buys.forEach((item) => {
      ids.push(item.product_Id)
    })
    this.setData({
      buys: buys,
      products: JSON.stringify(ids)
    })
  },
  _getDeliveryFee() {
    getDeliveryFee({
      data: {
        products: this.data.products,
        province: this.data.addressDetail.province,
        city: this.data.addressDetail.city
      },
      success: res => {
        if (res.state) {
          this.setData({
            deliveryFee: Number(res.data).toFixed(2)
          })
          this._getTotal()
        }
      }
    })
  },
  _getTotal() {
    let productTotal = 0
    this.data.buys.forEach((item) => {
      productTotal += item.count * item.price
    })
    this.setData({
      productTotal: productTotal.toFixed(2),
      total: (Number(productTotal) + Number(this.data.deliveryFee)).toFixed(2)
    })
  },
  setRemark(e) {
    this.setData({
      remark: e.detail.value
    })
  },
  setOrder() {
    let product = []
    this.data.buys.forEach((item) => {
      product.push({
        product_Id: item.product_Id,
        sku: [{
          id: item.sku_id,
          stock: item.count
        }]
      })
    })
    let delivery = {
      type: 2,
      receiver: {
        mid: this.data.addressDetail.mid
      }
    }
    let user = {
      openid: app.globalData.openid
    }
    let cards = []
    let remark = this.data.remark
    let obj = {
      product: product,
      delivery: delivery,
      user: user,
      cards: cards,
      remark: remark
    }
    getWXappPay({
      data: obj,
      success: res => {
        if (res.state) {
          let params = JSON.parse(res.data.parameters)
          wx.requestPayment({
            nonceStr: params.nonceStr,
            package: params.package,
            paySign: params.paySign,
            signType: params.signType,
            timeStamp: params.timeStamp,
            success: response => {
              wx.showToast({
                title: '支付成功',
                mask: true,
                duration: 2000,
                success: (e) => {
                  setTimeout(() => {
                    wx.navigateTo({
                      url: '../order-list/order-list',
                    })
                  },2000)
                }
              })
            },
            complete: response => {
              if (response.errMsg == "requestPayment:cancel" || response.errMsg== "requestPayment:fail cancel") {
                wXappUpdateOrder({
                  data: {
                    orderid: res.data.out_trade_no,
                    payStatus: 'fail',
                    payReamrk: '',
                    openid: app.globalData.openid
                  },
                  success: res => {
                    if (res.state) {
                      wx.showToast({
                        title: '支付失败',
                        icon: 'none',
                        mask: true,
                        duration: 2000,
                        success: (e) => {
                          setTimeout(() => {
                            wx.navigateTo({
                              url: '../order-list/order-list',
                            })
                          }, 2000)
                        }
                      })
                    }
                  }
                })
              }
            }
          })
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none',
            mask: true,
            duration: 1000
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})